/**
 * @desc today
 */
<template>
    <view class="today" v-if="!isWork">
        <nut-noticebar v-if="isCoach" text="学员时间未到场，可以点击头像拨打手机号！" :background="`rgba(251, 248, 220, 1)`"
            :color="`#D9500B`"></nut-noticebar>
        <view class="list">
            <view class="list-item" v-for="item in list" :key="item.id">
                <view class="list-item-head">
                    <text>{{ item.name }}(已预约{{ item.children.length }}人)</text>
                    <nut-button v-if="item.children.length < item.limit && !isCoach && isHas && item.endTime >= now"
                        @click="appointment(item.id, item.limit, item.endTime)" type="success">
                        点击预约</nut-button>
                    <nut-button @click="onOk" v-if="isAppointment(item.children) && item.endTime >= now" type="warning">
                        取消预约</nut-button>
                </view>
                <view class="list-item-person">
                    <view v-for="a in item.children" class="list-item-person-item" @click="call(a)">
                        <nut-avatar size="normal" :icon="a.avatarUrl">
                        </nut-avatar>
                        <text class="list-item-person-item-text">{{ a.name || a.nickName }}</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
    <nut-noticebar v-else text="今天教练休息....." :background="`rgba(251, 248, 220, 1)`" :color="`#D9500B`"></nut-noticebar>
</template>

<script>
const _ = db.command;
const openid = Taro.getStorageSync('openid');
import db from '../../server/index';
import Taro from '@tarojs/taro';
export default {
    name: 'Today',
    data() {
        return {
            isWork: false,
            list: [],
            isHas: false,
            phoneList: [],
            coachId: '',
            now: new Date().getTime(),
            isCoach: false, // 是否是教练
        }
    },
    onPullDownRefresh() {
        Taro.showLoading({
            title: '加载中',
        })
        this.startInit()
    },
    created() {
        this.startInit()
    },
    methods: {
        startInit() {
            // 检查是否是教练
            db.collection('coach').where({
                openid,
                stop: false
            }).get().then(({ data = [] }) => {
                this.isCoach = !!data.length
                // 教练
                if (this.isCoach) {
                    const { _id } = data[0];
                    this.coachId = _id;
                    this.checkTime()
                } else {
                    // 学员
                    db.collection('phone').where({
                        _openid: openid
                    }).get().then(({ data = [] }) => {
                        this.coachId = data[0].coachId;
                        this.checkTime()
                    })
                }
            })
        },
        checkTime() {
            let a = new Date();
            let year = a.getFullYear();
            let month = (a.getMonth() + 1 + '').padStart(2, 0);
            let day = (a.getDate() + '').padStart(2, 0);
            // 教练是否休息 
            db.collection('work').where({
                coachId: this.coachId,
                time: `${year}-${month}-${day}`
            }).get().then(({ data = [] }) => {
                this.isWork = !!data.length
            })
            db.collection('time').where({
                coachId: this.coachId
            }).get().then(({ data = [] }) => {
                data = data.sort((a, b) => a.index < b.index ? -1 : 1)
                this.list = data.map(item => {
                    return {
                        id: item._id,
                        limit: item.limit,
                        name: `${item.startTime}---${item.endTime}`,
                        endTime: new Date(`${year}-${month}-${day} ${item.endTime}`.replace(/-/g, '/')).getTime(),
                        children: []
                    }
                })
                if (this.isCoach) {
                    // 获取自己学院的所有手机号
                    db.collection('phone').where({
                        coachId: this.coachId
                    }).get().then(({ data = [] }) => {
                        this.phoneList = data
                        this.init();
                    })
                } else {
                    this.init()
                }
            })
        },

        init() {
            const { start, end } = this.getTime();
            const _ = db.command;
            db.collection('user').where({
                done: true,
                coachId: this.coachId,
                createTime: _.gte(start).and(_.lte(end))
            }).get().then(({ data = [] }) => {
                this.list.forEach(item => {
                    item.children = []
                })
                this.isHas = true
                data.forEach(item => {
                    if (this.isCoach) {
                        // 教练才能看姓名
                        this.phoneList.some(a => {
                            if (a._openid === item._openid) {
                                item.name = a.name
                                return true
                            }
                        })
                    }
                    if (item._openid === openid) {
                        this.isHas = false
                    }
                    this.list[this.list.findIndex((a) => item.type === a.id)].children.push(item)
                })
                this.list = this.list.map(item => {
                    item.children = item.children.sort((a, b) => {
                        return a.createTime - b.createTime > 0 ? 1 : -1
                    })
                    return item
                })
                Taro.stopPullDownRefresh();
                Taro.hideLoading();
            })
        },
        call(item) {
            if (!this.isCoach) {
                return
            }
            db.collection('phone').where({
                _openid: item._openid
            }).get().then(({ data = [] }) => {
                // 拨打手机号
                if (data.length) {
                    Taro.makePhoneCall({
                        phoneNumber: data[0].phone
                    })
                } else {
                    Taro.showToast({
                        title: '该学员尚未填写手机号!',
                        icon: 'none',
                        duration: 2000,
                        mask: true
                    })
                }
            })
        },
        // 今日起止时间
        getTime() {
            let a = new Date();
            let year = a.getFullYear();
            let month = (a.getMonth() + 1 + '').padStart(2, 0);
            let day = (a.getDate() + '').padStart(2, 0)
            const start = new Date(`${year}-${month}-${day} 00:00:00`.replace(/-/g, '/')).getTime();
            const end = new Date(`${year}-${month}-${day} 23:59:59`.replace(/-/g, '/')).getTime();
            return {
                start,
                end
            }
        },
        // 预约
        appointment(type, limit, endTime) {
            // 查询
            const { start, end } = this.getTime();
            const now = new Date().getTime();
            if (now >= endTime) {
                Taro.showToast({
                    title: '预约时间已过！',
                    icon: 'none',
                    duration: 2000,
                    mask: true
                })
                return
            }
            db.collection('user').where({
                done: false,
                _openid: openid,
                coachId: this.coachId,
                createTime: _.gte(start).and(_.lte(end))
            }).get().then(({ data = [] }) => {
                if (data.length > 3) {
                    Taro.showToast({
                        title: '今日预约取消次数上限，上限次数3次!',
                        icon: 'none',
                        duration: 2000,
                        mask: true
                    })
                } else {
                    db.collection('user').where({
                        done: true,
                        type,
                        coachId: this.coachId,
                        createTime: _.gte(start).and(_.lte(end))
                    }).get().then(({ data = [] }) => {
                        if (data.length >= limit) {
                            Taro.showToast({
                                title: '无法预约,人员上限！',
                                icon: 'none',
                                duration: 2000,
                                mask: true
                            })
                            this.init();
                            return
                        }
                        // 判断当前用户是否已经预约过了
                        db.collection('user').where({
                            done: true,
                            _openid: openid,
                            coachId: this.coachId,
                            createTime: _.gte(start).and(_.lte(end))
                        }).get().then(({ data = [] }) => {
                            if (data.length) {
                                Taro.showToast({
                                    title: '你已经预约过了,不能重复预约!',
                                    icon: 'none',
                                    duration: 2000,
                                    mask: true
                                })
                                this.isHas = false
                            } else {
                                const { avatarUrl, nickName } = Taro.getStorageSync('userInfo');
                                db.collection('user').add({
                                    data: {
                                        type,
                                        coachId: this.coachId,
                                        createTime: new Date().getTime(),
                                        avatarUrl, nickName,
                                        done: true
                                    }
                                }).then(() => {
                                    Taro.showToast({
                                        title: '预约成功!',
                                        icon: 'success',
                                        duration: 2000,
                                        mask: true
                                    })
                                    this.init();
                                })
                            }
                        })
                    })
                }
            })
        },
        // 是否预约过
        isAppointment(children) {
            return children.some(item => {
                return item._openid === openid
            })
        },
        // 取消预约
        onOk() {
            let a = new Date();
            let year = a.getFullYear();
            let month = (a.getMonth() + 1 + '').padStart(2, 0);
            let day = (a.getDate() + '').padStart(2, 0)
            const start = new Date(`${year}-${month}-${day} 00:00:00`.replace(/-/g, '/')).getTime();
            const end = new Date(`${year}-${month}-${day} 23:59:59`.replace(/-/g, '/')).getTime();
            db.collection('user').where({
                _openid: openid,
                done: true,
                createTime: _.gte(start).and(_.lte(end))
            }).get().then(({ data = [] }) => {
                if (!data.length) {
                    Taro.showToast({
                        title: '当前没有预约学车，请先预约！',
                        icon: 'none',
                        duration: 2000,
                        mask: true
                    })
                } else {
                    db.collection('user').where({
                        _openid: openid,
                        done: true,
                        createTime: _.gte(start).and(_.lte(end))
                    }).update({
                        data: {
                            done: false
                        }
                    }).then(() => {
                        this.init();
                        Taro.showToast({
                            title: '取消预约成功!',
                            icon: 'success',
                            duration: 2000,
                            mask: true
                        })
                    })
                }
            })
        }
    },
}
</script>

<style lang="less">
.today {
    .list {
        height: 100vh;

        &-item {
            padding: 0 5px;
            min-height: 30vh;

            &-head {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 60px;
                z-index: 1000;
            }

            &-person {
                display: flex;
                flex-wrap: wrap;

                &-item {
                    display: flex;
                    align-items: center;
                    height: 50px;
                    width: 50%;

                    &-text {
                        margin-left: 6px;
                        font-size: 14px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }
            }
        }
    }
}
</style>
